import 'package:flutter/foundation.dart';
import '../services/api_service.dart';
import '../models/health_news.dart';
import '../services/cache_service.dart';
import '../services/log_service.dart';

class HealthNewsProvider with ChangeNotifier {
  final ApiService _apiService = ApiService();
  final CacheService _cacheService = CacheService();

  List<HealthNews> _newsList = [];
  bool _isLoading = false;
  bool _hasError = false;
  String _errorMessage = '';
  int _currentPage = 1;
  int _totalResults = 0;
  bool _hasMoreData = true;
  bool _isRandomMode = false;
  String _searchKeyword = '';
  int _retryCount = 0;
  final int _maxRetries = 3;

  // Getters
  List<HealthNews> get newsList => _newsList;
  bool get isLoading => _isLoading;
  bool get hasError => _hasError;
  String get errorMessage => _errorMessage;
  int get currentPage => _currentPage;
  int get totalResults => _totalResults;
  bool get hasMoreData => _hasMoreData;
  bool get isRandomMode => _isRandomMode;
  bool get hasMoreResults => _newsList.length < _totalResults;
  String get searchKeyword => _searchKeyword;

  // 初始加载
  Future<void> loadInitialNews() async {
    _currentPage = 1;
    await fetchHealthNews();
  }

  // 搜索新闻
  Future<void> searchNews(String keyword) async {
    _searchKeyword = keyword;
    _currentPage = 1;
    _newsList = [];
    notifyListeners();
    await fetchHealthNews();
  }

  // 加载更多
  Future<void> loadMoreNews() async {
    if (!hasMoreResults || _isLoading) return;

    _currentPage++;
    await fetchHealthNews();
  }

  // 切换随机模式
  Future<void> toggleRandomMode() async {
    _isRandomMode = !_isRandomMode;
    _currentPage = 1;
    _newsList = [];
    notifyListeners();
    await fetchHealthNews();
  }

  // 获取健康资讯
  Future<void> fetchHealthNews() async {
    _isLoading = true;
    _errorMessage = '';
    notifyListeners();

    try {
      // 先尝试从缓存获取
      final cacheKey =
          'news_${_currentPage}_${_searchKeyword}_${_isRandomMode}';
      final cachedData = await _cacheService.getData(cacheKey);

      if (cachedData != null) {
        // 使用缓存数据
        if (_currentPage == 1) {
          _newsList = List<HealthNews>.from(
              (cachedData as List).map((item) => HealthNews.fromJson(item)));
        } else {
          _newsList.addAll(List<HealthNews>.from(
              (cachedData as List).map((item) => HealthNews.fromJson(item))));
        }
        _isLoading = false;
        notifyListeners();

        // 在后台刷新缓存
        _refreshCacheInBackground(cacheKey);
        return;
      }

      // 没有缓存，请求网络
      final response = await _apiService.getHealthNews(
        page: _currentPage,
        keyword: _searchKeyword.isNotEmpty ? _searchKeyword : null,
        isRandom: _isRandomMode,
      );

      // 更新数据并缓存
      if (_currentPage == 1) {
        _newsList = response.news;
      } else {
        _newsList.addAll(response.news);
      }

      _totalResults = response.allnum;

      // 缓存新闻列表数据 (转换为可序列化的列表)
      final newsJsonList = response.news.map((news) => news.toJson()).toList();
      await _cacheService.saveData(cacheKey, newsJsonList);

      _isLoading = false;
      _retryCount = 0;
      notifyListeners();
    } catch (e) {
      // 处理错误，增加重试逻辑
      if (_retryCount < _maxRetries) {
        _retryCount++;
        await Future.delayed(Duration(seconds: _retryCount));
        return fetchHealthNews();
      }

      _isLoading = false;
      _errorMessage = e.toString();
      notifyListeners();
    }
  }

  // 在后台刷新缓存
  Future<void> _refreshCacheInBackground(String cacheKey) async {
    try {
      final response = await _apiService.getHealthNews(
        page: _currentPage,
        keyword: _searchKeyword.isNotEmpty ? _searchKeyword : null,
        isRandom: _isRandomMode,
      );

      await _cacheService.saveData(
          cacheKey, response.news.map((news) => news.toJson()).toList());
    } catch (e) {
      // 后台刷新失败不影响UI
      LogService().warning('后台缓存刷新失败: $e');
    }
  }

  // 刷新数据
  Future<void> refreshNews() async {
    _currentPage = 1;
    await fetchHealthNews();
  }

  // Reset state
  void resetState() {
    _newsList = [];
    _isLoading = false;
    _hasError = false;
    _errorMessage = '';
    _currentPage = 1;
    _totalResults = 0;
    _hasMoreData = true;
    _isRandomMode = false;
    _searchKeyword = '';
    notifyListeners();
  }
}
